#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <stdint.h>
#include <avr/eeprom.h>
#include <stdlib.h>
#include <math.h>
#include "lcd.h"



#include <util/delay.h>


//display defines:
#ifndef F_CPU
/*! \brief Define default CPU frequency, if this is not already defined. */
#define F_CPU 32000000UL
#endif

void clock_init(void);
void port_init(void);

int main(void){

	clock_init();
	port_init();
	PORTE.OUTTGL = PIN0_bm;		// Toggle PORTE.PIN0

	lcd_init(LCD_DISP_ON);

	PORTE.OUTTGL = PIN0_bm;		// Toggle PORTE.PIN0


	lcd_clrscr();				// clear display and home cursor

    lcd_puts("LCD Test Line 1\n");	    // put string to display (line 1) with linefeed

	while(1)
	{
	PORTE.OUTTGL = PIN0_bm;		// Toggle PORTE.PIN0
	_delay_ms(1000);
	}

}
void clock_init(void){

	// --startup clk: internal 2MHz
	// --enable 32MHz clk
	OSC.CTRL|=OSC_RC32MEN_bm;

	// --wait for stable 32MHz clk
	while (!(OSC.STATUS & OSC_RC32MRDY_bm)) {}

	// --DFLL enabled on 32MHz clk with internal 32KHz oscillator
	DFLLRC32M.CTRL|=DFLL_ENABLE_bm;

	// --switch to 32MHz clk
	//   clock control in module CLK.
	//   timed sequence needed !!
	CCP=CCP_IOREG_gc; // change protected IO reg

	CLK.CTRL = (CLK.CTRL & ~CLK_SCLKSEL_gm) | CLK_SCLKSEL_RC32M_gc;

	CLK.PSCTRL = CLK_PSADIV_1_gc | CLK_PSBCDIV_1_1_gc; //divide A,B,C by one
}

void port_init(void){
	// set PIN0 as output
	PORTE.DIRSET = PIN0_bm;
//	PORTD.DIRSET = PIN7_bm;
}
